﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Threading;

namespace VisaValeCheck
{
    internal static class PluginHelper
    {
        private static List<VisaValeCheckPluginBase> _plugins = new List<VisaValeCheckPluginBase>();        
        private delegate void X();                

        public static event VisaValeCheckPluginBase.EventoNoPluginDelegate EventoNoPlugin;

        public static void CarregarPlugins(Visa objVisa)
        {
            foreach (string f in Directory.GetFiles(LocalExe(), "*.dll"))
            {
                try
                {
                    Assembly asm = Assembly.LoadFile(f);
                    Type[] tipos = asm.GetExportedTypes();
                    IEnumerable<Type> tiposOk = tipos.TakeWhile((a) => a.IsSubclassOf(typeof(VisaValeCheckPluginBase)));
                    foreach (Type t in tiposOk)
                    {                         
                        VisaValeCheckPluginBase instancia = Activator.CreateInstance(t) as VisaValeCheckPluginBase;                        
                        instancia.Evento += EventoNoPlugin;
                        _plugins.Add(instancia);
                    }
                }
                catch
                {

                }
            }
        }

        public static void RodarPlugins(VisaSaldo visaSaldo)
        {
            foreach (VisaValeCheckPluginBase plugin in _plugins)
            {
                /*Thread th = new Thread(new ThreadStart(() =>
                {*/
                    plugin.Executar(visaSaldo);
               /* }
                ));
                try
                {
                    th.Start();                    
                }
                catch
                {
                }*/
            }
        }        

        private static string LocalExe()
        {
            Assembly asm = Assembly.GetEntryAssembly();
            string[] pathPieces = asm.Location.Split('\\');
            string joinedPieces = string.Join("\\", pathPieces.Take(pathPieces.Length - 1).ToArray());
            return joinedPieces;        
        }
    }
}
